<template>
  <div>
    <vxe-grid 
      v-bind="myAttrs"
      ref="xGrid"
    >
      <template v-for="slot in Object.keys($slots)" #[slot]="data">
        <slot :name="slot" v-bind="data"></slot>
      </template>
    </vxe-grid>
  </div>
</template>

<script lang="ts" setup>
  import { ref, useAttrs, onMounted, nextTick, computed } from 'vue'
  import { useSortable } from '/@/hooks/web/useSortable';
  import { isNullAndUnDef } from '/@/utils/is';
  import type { VxeGridProps, VxeGridInstance, VxeGridPropTypes } from 'vxe-table';
  import { cloneDeep } from 'lodash-es';
  
  const xGrid = ref<VxeGridInstance>()
  const attrs = useAttrs()
  const columns = ref<VxeGridPropTypes.Columns>(attrs.columns as VxeGridPropTypes.Columns)

  const myAttrs = computed<VxeGridProps>(() => {
    return {
      ...cloneDeep(attrs),
      ...{
        columns: columns.value
      }
    }
  })

  const sortTable = () => {
    const el = document.querySelector('.vxe-table--header .vxe-header--row') as HTMLElement
    nextTick(() => {
      const { initSortable } = useSortable(el, {
        handle: '.vxe-header--column',
        onEnd: (evt) => {
          const { oldIndex, newIndex } = evt;
          if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || oldIndex === newIndex) {
            return;
          }
          // Sort column
          const arr = cloneDeep(columns.value)

          if (oldIndex > newIndex) {
            arr.splice(newIndex, 0, arr[oldIndex]);
            arr.splice(oldIndex + 1, 1);
          } else {
            arr.splice(newIndex + 1, 0, arr[oldIndex]);
            arr.splice(oldIndex, 1);
          }
          columns.value = arr
        },
      });
      initSortable();
    })
  }

  const getRef = () => {
    return xGrid.value
  }

  onMounted(() => {
    sortTable()
  })

  defineExpose({
    getRef
  })
</script>

<style lang="less" scoped>

</style>